<template>
  <div class="register-container">
    <div class="register-background">
      <div class="cyber-grid"></div>
    </div>
    
    <div class="register-box">
      <div class="register-header">
        <el-icon :size="50" class="logo-icon"><UserFilled /></el-icon>
        <h1 class="register-title neon-text">用户注册</h1>
        <p class="register-subtitle">Create Your Account</p>
      </div>

      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef" class="register-form">
        <el-form-item prop="username">
          <el-input 
            v-model="registerForm.username" 
            placeholder="用户名"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="email">
          <el-input 
            v-model="registerForm.email" 
            placeholder="邮箱"
            size="large"
            clearable
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password" 
            type="password"
            placeholder="密码"
            size="large"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword" 
            type="password"
            placeholder="确认密码"
            size="large"
            show-password
            @keyup.enter="handleRegister"
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="agree">
          <el-checkbox v-model="registerForm.agree">
            我已阅读并同意 <el-button type="text" size="small">《用户协议》</el-button>
          </el-checkbox>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            size="large" 
            :loading="loading"
            @click="handleRegister"
            class="register-button"
          >
            <el-icon v-if="!loading"><Right /></el-icon>
            {{ loading ? '注册中...' : '注 册' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="register-footer">
        <el-button type="text" @click="$router.push('/login')">
          已有账号？立即登录
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { authAPI } from '@/api'

const router = useRouter()
const registerFormRef = ref(null)
const loading = ref(false)

const registerForm = reactive({
  username: '',
  email: '',
  password: '',
  confirmPassword: '',
  agree: false
})

const validatePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const validateAgree = (rule, value, callback) => {
  if (!value) {
    callback(new Error('请阅读并同意用户协议'))
  } else {
    callback()
  }
}

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePassword, trigger: 'blur' }
  ],
  agree: [
    { validator: validateAgree, trigger: 'change' }
  ]
}

const handleRegister = async () => {
  if (!registerFormRef.value) return
  
  await registerFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      
      try {
        const response = await authAPI.register({
          username: registerForm.username,
          email: registerForm.email,
          password: registerForm.password,
          confirm_password: registerForm.confirmPassword
        })
        
        ElMessage.success(response.message || '注册成功！即将跳转到登录页面...')
        
        // 跳转到登录页
        setTimeout(() => {
          router.push('/login')
        }, 1500)
      } catch (error) {
        console.error('注册失败:', error)
        let errorMsg = '注册失败'
        
        if (error.response?.data) {
          const errData = error.response.data
          if (typeof errData === 'object') {
            // 处理字段级错误
            const firstError = Object.values(errData)[0]
            errorMsg = Array.isArray(firstError) ? firstError[0] : firstError
          } else if (typeof errData === 'string') {
            errorMsg = errData
          }
        }
        
        ElMessage.error(errorMsg)
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.register-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: hidden;
  background: linear-gradient(135deg, #0a0e27 0%, #151a35 50%, #0a0e27 100%);
}

.register-background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.cyber-grid {
  position: absolute;
  width: 100%;
  height: 100%;
  background-image: 
    linear-gradient(rgba(0, 212, 255, 0.1) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 212, 255, 0.1) 1px, transparent 1px);
  background-size: 50px 50px;
  animation: grid-move 20s linear infinite;
}

@keyframes grid-move {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(50px, 50px);
  }
}

.register-box {
  position: relative;
  z-index: 1;
  width: 450px;
  padding: 50px 40px;
  background: linear-gradient(135deg, var(--cyber-bg-secondary) 0%, #1a2040 100%);
  border: 2px solid var(--cyber-secondary);
  border-radius: 20px;
  box-shadow: 0 0 50px rgba(0, 212, 255, 0.5);
  backdrop-filter: blur(10px);
  animation: float 6s ease-in-out infinite;
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-10px);
  }
}

.register-header {
  text-align: center;
  margin-bottom: 30px;
}

.logo-icon {
  color: var(--cyber-secondary);
  animation: neon-pulse 2s ease-in-out infinite;
}

.register-title {
  font-size: 28px;
  margin: 20px 0 10px;
  color: var(--cyber-secondary);
  font-family: 'Courier New', monospace;
  letter-spacing: 2px;
}

.register-subtitle {
  font-size: 12px;
  color: var(--cyber-text-dim);
  letter-spacing: 3px;
  text-transform: uppercase;
}

.register-form {
  margin-top: 30px;
}

.register-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.register-form :deep(.el-input__wrapper) {
  background: rgba(10, 14, 39, 0.5) !important;
  border: 2px solid rgba(0, 212, 255, 0.3);
  transition: all 0.3s;
}

.register-form :deep(.el-input__wrapper:hover),
.register-form :deep(.el-input__wrapper.is-focus) {
  border-color: var(--cyber-secondary);
  box-shadow: 0 0 15px rgba(0, 212, 255, 0.5);
}

.register-form :deep(.el-checkbox__label) {
  color: var(--cyber-text);
}

.register-form :deep(.el-checkbox__label .el-button) {
  color: var(--cyber-secondary);
}

.register-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  letter-spacing: 5px;
  margin-top: 10px;
  background: linear-gradient(135deg, var(--cyber-secondary) 0%, var(--cyber-primary) 100%) !important;
}

.register-footer {
  text-align: center;
  margin-top: 20px;
}

.register-footer :deep(.el-button) {
  color: var(--cyber-primary);
  font-size: 14px;
}

.register-footer :deep(.el-button:hover) {
  color: var(--cyber-secondary);
}
</style>
